package com.wavercaz.freeforum.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

// 代码生成工具
public class GenUtils {

    // 获取文件名
    public static String getFileName(String template,String className, String packageName) {
        String packagePath = "main" + File.separator+"java"+File.separator;
        if(StringUtils.isNoneEmpty(packagePath)) {
            packagePath += packageName.replace(".",File.separator)+ File.separator;
        }
        if(template.contains("Controller.java.vm")) {
            return packagePath+"controllers"+File.separator+className+"Controller.java";
        }
        if(template.contains("Service.java.vm")) {
            return packagePath+"services"+File.separator+className+"Service.java";
        }
        if(template.contains("ServiceImpl.java.vm")) {
            return packagePath+"services"+File.separator+"impl"+File.separator+className+"ServiceImpl.java";
        }
        if(template.contains("Mapper.java.vm")) {
            return packagePath+"mappers"+File.separator+className+"Mapper.java";
        }
        if(template.contains("api.js.vm")) {
            return packagePath+"api"+File.separator+className.toLowerCase()+".js";
        }
        return null;
    }

    // 生成代码
    public static void generatorCode(Map<String,Object> data, List<String> templates, ZipOutputStream zip) throws IOException {
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        VelocityContext context = new VelocityContext(data);
        for(String template: templates) {
            Template tpl = Velocity.getTemplate(template,"UTF-8");
            StringWriter sw = new StringWriter();
            tpl.merge(context,sw);
            String fileName = getFileName(template, data.get("className").toString(), data.get("package").toString());
            zip.putNextEntry(new ZipEntry(fileName));
            IOUtils.write(sw.toString(),zip,"UTF-8");
            IOUtils.closeQuietly(sw);
        }
    }
}
